package com.moter.demo01.juc.basic;

import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 * 独占锁(写锁)
 * 共享锁(读锁)
 * 读-读 √
 * 读-写 ×
 * 写写 ×
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        CacheDemo cacheDemo = new CacheDemo();
        for (int i = 0; i < 10; i++) {
            int temp = i;
            new Thread(()->{
                cacheDemo.put(temp+"",temp+"");
            }).start();
        }
        for (int i = 0; i < 10; i++) {
            int temp = i;
            new Thread(()->{
                cacheDemo.get(temp+"");
            }).start();
        }
    }
}
class CacheDemo{
    private volatile Map<String,String> map;
    private ReadWriteLock readWriteLock;

    public CacheDemo() {
        map=new Hashtable<>();
        readWriteLock = new ReentrantReadWriteLock();
    }
    public void put(String key,String value){
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "准备写入");
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写入完成");
        }finally {
            readWriteLock.writeLock().unlock();
        }
    }
    public void get(String key){
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "准备读取");
            map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取完成");
        }finally {
            readWriteLock.readLock().unlock();

        }
    }
}